package lv.accenture.bootcamp;

public class Koch {
	
	public String sampleSVG(int order) {

		StringBuffer buf = new StringBuffer();
		buf.append("<?xml version='1.0'?>\n");
		buf.append("<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.0//EN'\n");
		buf.append("'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'>\n");
		buf.append("<svg width='100cm' height='100cm' viewBox='0 0 2 2'>\n");
		buf.append("<title>Hilbert curve</title>\n");
		buf.append("<desc>This is a sample SVG file for Hilbert curve</desc>\n");
		buf.append("<rect x='0' y='0' width='2' height='2' fill='#fdfdfd'/>\n");
		buf.append("<g transform=\"translate(0,2) scale(1 -1)\" style=\"stroke:#006699;stroke-width:0.001;fill:#c0c0c0;\">\n");
		buf.append(kochSVG(order) + "\n");
		buf.append("</g>\n");
		buf.append("</svg>\n");

		return buf.toString();
	}
	
	public String draw(double x1, double y1, double x2, double y2, int i, int order){
		
		double xx1, yy1, xx2, yy2, xx3, yy3;
		
		i++;
		
		xx1 = (x2 - x1)/3 + x1;
		yy1 = (y2 - y1)/3 + y1;
		
		xx2 = (x2 - x1)/3*2 + x1;
		yy2 = (y2 - y1)/3*2 + y1;
		
		xx3 = (xx2-xx1)*Math.cos(1.047) - (yy2-yy1)*Math.sin(1.047) + xx1; // 1.047 = 60 grades
		yy3 = (xx2-xx1)*Math.sin(1.047) + (yy2-yy1)*Math.cos(1.047) + yy1;
		
		if (i < order) {
			return "" + draw(x1,y1,xx1,yy1, i, order) + "," 
					  + draw(xx1,yy1,xx3,yy3, i, order) + "," 
					  + draw(xx3,yy3,xx2,yy2, i, order) + "," 
					  + draw(xx2,yy2,x2,y2, i, order);
		} else {
			return "" + x1 + "," + y1 + ","
					  + xx1 + "," + yy1 + ","
					  + xx3 + "," + yy3 + ","
					  + xx2 + "," + yy2 + ","
					  + x2 + "," + y2;
		}
	}
	
	public String kochSVG(int order) {
		String begin = new String();
		int i = 0;
		
		begin = draw(0.5, 0.5, 1, 1.366, i, order) + "," + 
				draw(1, 1.366, 1.5, 0.5, i, order) + "," + 
				draw(1.5, 0.5, 0.5, 0.5, i, order);
		return "<path d=\"M," + begin + "\"/>";
	}
}
